import Axios from 'axios';
import qs from 'qs';
import {auth} from '../utils/auth'
import router from '../router/lazy'
import {message} from 'ant-design-vue'

export const axios = Axios.create({
  baseURL: "http://127.0.0.1:8080/api", // 通常配置基础的接口入口地址
  timeout: 60000, // 请求超时时间
  headers: {// 这里可设置所有的请求头
    "Access-Control-Allow-Origin": "*",
  },
  withCredentials: true,//是否允许发送Cookie 如果为true 则服务器的 Access-control-Allow-Credentials 必须为 true 来源为 XMLHttpRequest的withCredentials配置项
});

//网络请求添加Token
axios.interceptors.request.use(config => {
  if (auth.getToken()) {
    config.headers.Authorization = auth.getToken()
  }
  return config
}, error => {
  return Promise.reject(error);
});

//检测返回结果
axios.interceptors.response.use(
  response => {

    console.log("response.headers:" + JSON.stringify(response.headers))
    //服务端更新token
    if (response.headers.authorization) {
      console.log("服务器更新Token");
      auth.setToken(response.headers.authorization)
    }

    if (response.data.status !== 200 || response.status !== 200) {
      console.log("返回错误信息:" + JSON.stringify(response.data));
      return onError({
        status: response.data.status || response.status,
        message: response.data.message || response.message
      })
    } else {
      return response;
    }
  },
  error => {
    console.log("发生错误:" + JSON.stringify(error));
    if (error.response) {
      return onError({
        status: response.data.status || error.response.status,
        message: response.data.message || response.message
      })
    }

  });

const onError = (error) => {
  switch (error.status) {
    //登陆失败
    case 401:
      auth.removeToken();
      let url = router.currentRoute.fullPath;
      console.log(url);
      let query = null;
      if (url && url !== "/login" && url !== "/") {
        query = {redirect: url}
      }
      router.replace({
        path: 'login',
        query: query
      });
      break;
  }
  message.error(error.message);
  return Promise.reject(error);
};

/**
 * 网络链接
 * @param url 地址
 * @param params 参数
 */
const request = function (url, params) {

  return axios.post(url, qs.stringify(params)).then(res => {
    if (res) {
      if (res.data) {
        return res.data
      }
    }
  })
};

export const loginFirst = () => request("/login/LoginFirst", {});

export const loginSecond = (username, password) => request("/login/LoginSecond", {username, password});

export const getUserList = (page, pageSize, searchText) => request("/user/getUserList", {page, pageSize, searchText});

export const logout = (token) => request("/login/logout", {token});

export const getUserInfo = () => request("/user/getUserInfo")
